<script setup>
import {onMounted, ref} from "vue";
import router from "@/router";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import {map} from "core-js/internals/array-iteration";
//页面加载时初始化一个map实例，加载百度地图，并增加点击事件监听器，当点击地图时自动记录经纬度，并根据经纬度反向检索地址并保存，同时弹出站点信息弹窗
onMounted(
    ()=>{
      if (typeof BMapGL !== 'undefined') {
        var map = initMap();
        var geoc=new BMapGL.Geocoder();
        map.addEventListener('click', function (e) {
          isSearchAddress.value=false;
          isDirectInput.value=false;
          position.value=e.latlng;
          console.log(position.value);
          var marker1 = new BMapGL.Marker(new BMapGL.Point(e.latlng.lng, e.latlng.lat));
          map.addOverlay(marker1);
          geoc.getLocation(e.latlng,function (rs){
            var addComp=rs.addressComponents;
            var address=addComp.province+','+addComp.city+','+addComp.district+','+addComp.street+','+addComp.streetNumber;
            addressList.value = address.split(',');
          })
        });
      } else {
        console.error('百度地图API加载失败');
      }
    }
)
//该按钮默认显示，当点击后即可转换为“提交地址”
const isSearchAddress=ref(true);

const isDirectInput=ref(true);
//用于分段展示省、市、区/县、街道等信息
const addressList=ref({});
//记录站点地址的对象
const address=ref();
//记录站点经纬度的对象
const position=ref();
//记录站点信息的对象
const stationInfo=ref({
  stationName:'',
  stationLocation:'',
  stationPosition:'',
  createTime:'',
  bindVehicleList:[]
})
//站点信息输入弹窗的标题
const stationDialogTitle=ref("新增站点信息");
//站点信息输入弹窗的可视参数
const stationDialogVisible=ref(false);
//绑定车辆弹窗的可视参数
const bindDialogVisible=ref(false);
//按钮的可视参数，当没有绑定车辆时显示绑定车辆按钮，绑定车辆后显示车辆的信息
const bindVehicleOrNot=ref(true);
//用于接收可绑定车辆信息的数组
const vehicleInfoList=ref([]);
//用于记录选中的车辆的信息
const selectedVehicle=ref([]);
//用于初始化map实例的对象
const initMap=()=>{
  var map = new BMapGL.Map("container");
  map.centerAndZoom(new BMapGL.Point(116.404, 39.928), 15);
  map.enableScrollWheelZoom(true);
  return map;
}
//点选站点并确认地址后，将地址信息进行提交
const commitPosition=()=>{
  if (addressList.value.length>0){
    address.value='';
    for (let i=0 ; i<addressList.value.length;i++){
      if (addressList.value[i] == 'undefined'){
        continue;
      }
      console.log(addressList.value[i]);
      address.value+=addressList.value[i];
    }
  }
  console.log(address.value);
  stationDialogVisible.value=true;
}
//用于检索直接输入的北京市内的地址的经纬度，目前不支持展示多个地点的信息，待完善
//todo 完善展示多个地点信息的功能
const searchAddress=()=>{
  position.value={};
 var map1 = initMap();
 var myGeo=new BMapGL.Geocoder();
 myGeo.getPoint(address.value,(point)=>{
   if (point){
     map1.centerAndZoom(point,16);
     map1.addOverlay(new BMapGL.Marker(point,{title: address.value}));
     position.value=point;
     console.log(position.value);
   }
   else {
     alert("您输入的地址有误");
   }
 },'北京市');
  isSearchAddress.value=false;

}
//用于管理站点弹窗的关闭事件
const handleClose=()=>{
  if (confirm("您确定要关闭地址点选窗口么？若关闭则返回站点管理页面")){
    addressList.value={};
    position.value={};
    stationDialogVisible.value=false;
    router.push("/stationInfo");
  }
}
//新增站点的方法
const addStation=()=>{
  commitBindVehicle();
  stationInfo.value.stationLocation=address.value;
  stationInfo.value.stationPosition=JSON.stringify(position.value);
  console.log(stationInfo.value);
  let data=qs.stringify(stationInfo.value);
  axios.post(BASE_URL+'/station/add',data)
      .then((response)=>{
        if (response.data.code == 2000){
          ElMessage.success("站点新增成功");
          stationDialogVisible.value=false;
          bindVehicleOrNot.value=true;
          router.push("/stationInfo");
        }
        else {
          ElMessage.error(response.data.msg);
        }
      })
}
//用于从后端搜索可绑定的车辆的信息的方法
const getVehicleInfo=()=>{
  bindDialogVisible.value=true;
  axios.get(BASE_URL+'/vehicle/getVehicle')
      .then((response)=>{
        if (response.data.code == 2000){
          vehicleInfoList.value=[];
          vehicleInfoList.value=response.data.data;
          console.log(vehicleInfoList);
        }
        else {
          ElMessage.error(response.data.msg);
        }
      })
}
//用于记录选择对象改变的方法
const handleSelectChange=(selection)=>{
  selectedVehicle.value=selection;
  // console.log(selectedVehicle.value);
}
//重置地址检索
//todo 完善重置功能，目前无法完全重置
const reSelectLocation=()=>{
  isDirectInput.value=true;
  addressList.value=[];
}
//用于管理绑定车辆弹窗的关闭事件
const closeBindDialog=()=>{
  for (let i=0;i<vehicleInfoList.value.length;i++){
    vehicleInfoList.value[i].isSelected=false;
  }
  bindVehicleOrNot.value = false;
  bindDialogVisible.value = false;
}
//提交绑定该站点的车辆信息的方法
const commitBindVehicle=()=> {
  for (const vehicle of selectedVehicle.value) {
    stationInfo.value.bindVehicleList.push(vehicle.id);
  }
  console.log(stationInfo.value.bindVehicleList);
}
//todo 移除绑定该站点的车辆的方法，目前未完善
const removeBindVehicle=(index)=>{
  selectedVehicle.value.splice(index,1);
}

const showSelectedVehicle=()=>{
  // for (let i=0;i<vehicleInfoList.value.length;i++){
  //   vehicleInfoList.value[i].isSelected=(selectedVehicle.value.indexOf(vehicleInfoList.value[i]) != -1);
  // }
  bindDialogVisible.value=true;
  console.log(vehicleInfoList.value);
}



</script>

<template>

  <!-- 用于显示地图选点后的站点位置信息或显示直接检索的地址内容 -->
  <el-card>
    <el-row :gutter="10">
      <el-col :span="20">
        <el-input placeholder="请输入地址或点选地图进行选择" v-if="isDirectInput" v-model="address"></el-input>
        <el-form :inline="true" v-else>
          <el-form-item label="省区名称">
            <el-input type="text" style="width: 70px" v-model="addressList[0]"></el-input>
          </el-form-item>
          <el-form-item label="城市名称">
            <el-input type="text" style="width: 70px" v-model="addressList[1]"></el-input>
          </el-form-item>
          <el-form-item label="区域名称">
            <el-input type="text" style="width: 70px" v-model="addressList[2]"></el-input>
          </el-form-item>
          <el-form-item label="街道名称" >
            <el-input type="text" style="width: 90px" v-model="addressList[3]" placeholder="请输入街道名称" ></el-input>
          </el-form-item>
          <el-form-item label="详细信息">
            <el-input type="text" v-model="addressList[4]" style="width: 350px"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="searchAddress" v-if="isSearchAddress">检索地址</el-button>
        <el-button type="success" @click="commitPosition" v-else>提交地址</el-button>
        <el-button type="warning" @click="reSelectLocation">清空信息</el-button>
      </el-col>
    </el-row>
  </el-card>
  <!-- 展示地图的容器 -->
  <div id="container"></div>

  <!-- 新建站点时输入站点信息的弹窗 -->
  <el-dialog :title="stationDialogTitle" v-model="stationDialogVisible" :before-close="handleClose">
    <el-form label-position="top">
      <el-form-item label="站点名称">
        <el-input type="text" placeholder="请输入" style="width: 400px" v-model="stationInfo.stationName"></el-input>
      </el-form-item>
      <el-form-item label="站点位置">
        <el-input type="text" v-model="address" >
          <template #append>
            <el-button type="info">
              <el-icon><MapLocation /></el-icon>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item>
            <el-date-picker type="date" placeholder="请选择创建日期" v-model="stationInfo.createTime"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item>
            <el-button type="primary" @click="getVehicleInfo" v-if="bindVehicleOrNot">请选择绑定的车辆</el-button>
            <div style="max-height: 30px;overflow: auto;width: 300px" v-else>
              <el-tag v-for="(vehicle,index) in selectedVehicle" closable @close="removeBindVehicle(index)">{{vehicle.license}}</el-tag>
              <el-button class="button-new-tag" size="small" @click="showSelectedVehicle">新增车辆</el-button>
            </div>

          </el-form-item>
        </el-col>
        <el-form-item style="position: relative;left: 600px">
          <el-button type="primary" @click="addStation">新建</el-button>
          <el-button type="warning" @click="handleClose">取消</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
  <!-- 展示可绑定车辆信息的弹窗 -->
  <el-dialog title="车辆绑定弹窗" v-model="bindDialogVisible" width="80%"  >
    <el-form>
      <el-form-item>
        <el-table ref="table" :data="vehicleInfoList" style="height:500px;overflow: auto" @selection-change="handleSelectChange" @select="">
          <el-table-column type="selection"></el-table-column>
          <el-table-column type="index" label="序号" width="70"/>
          <el-table-column label="车牌号" prop="license" align="center"/>
          <el-table-column label="车辆名称" prop="name" align="center"/>
          <el-table-column label="车辆品牌" prop="brand" align="center"/>
          <el-table-column label="车辆型号" prop="model" align="center"/>
          <el-table-column label="车辆类型" prop="type" align="center"/>
          <el-table-column label="车辆状态" prop="status" align="center"/>
          <el-table-column label="车辆颜色" prop="color" align="center"/>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="closeBindDialog">确认</el-button>
        <el-button type="info">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
#container {
  overflow: hidden;
  width: 100%;
  height: 100vh;
  margin: 0;
  font-family: "微软雅黑";
}
</style>